package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.mapper.UserShopStatisticsMapper;
import com.qys.livesMall.app.user.model.dto.app.AppUserInfoTeamIncomeDTO;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.vo.app.AppUserInfoTeamDetailVo;
import com.qys.livesMall.app.user.service.AppUserRelationService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.app.user.service.UserStatisticsDayLogService;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.enums.FinanceMessageEnum;
import com.qys.livesMall.finance.mapper.FinanceShopAccountDetailMapper;
import com.qys.livesMall.finance.mapper.FinanceShopAccountMapper;
import com.qys.livesMall.finance.model.dto.user.UserInfoTeamIncomeDTO;
import com.qys.livesMall.finance.model.entity.shop.FinanceShopAccount;
import com.qys.livesMall.finance.model.vo.AppUserInfoTeamIncomeVO;
import com.qys.livesMall.finance.service.FinanceShopAccountService;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import com.qys.livesMall.shop.constants.ShopConstant;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.mapper.H2ShopRechargeWithdrawalMapper;
import com.qys.livesMall.shop.modal.entity.H2ShopBase;
import com.qys.livesMall.shop.modal.entity.H2ShopStatisticsInfo;
import com.qys.livesMall.shop.modal.entity.ShopIncomeConfig;
import com.qys.livesMall.shop.modal.entity.ShopStatisticsTeam;
import com.qys.livesMall.shop.mapper.ShopStatisticsTeamMapper;
import com.qys.livesMall.shop.modal.vo.AppShopInfoTeamVo;
import com.qys.livesMall.shop.modal.vo.UserAgentInfoVO;
import com.qys.livesMall.shop.service.H2ShopStatisticsInfoService;
import com.qys.livesMall.shop.service.ShopIncomeConfigService;
import com.qys.livesMall.shop.service.ShopStatisticsTeamService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 团队统计数据 服务实现类
 * </p>
 *
 * @author
 * @since 2023-11-03
 */
@Slf4j
@Service
public class ShopStatisticsTeamServiceImpl extends ServiceImpl<ShopStatisticsTeamMapper, ShopStatisticsTeam> implements ShopStatisticsTeamService {
    @Resource
    private AppUserRelationService relationService;
    @Resource
    private H2ShopBaseDao h2ShopBaseService;
    @Resource
    private H2ShopStatisticsInfoService h2ShopStatisticsInfoService;
    @Resource
    private FinanceShopAccountService financeShopAccountService;
    @Resource
    private H2ShopRechargeWithdrawalMapper h2ShopRechargeWithdrawalMapper;
    @Resource
    private FinanceShopAccountDetailMapper financeShopAccountDetailMapper;
    @Resource
    private MessageServer messageServer;
    @Resource
    private IH2AppUserService appUserService;
    @Resource
    private ShopIncomeConfigService shopIncomeConfigService;
    @Resource
    private FinanceShopAccountMapper financeShopAccountMapper;

    @Override
    public ShopStatisticsTeam getByShopId(Long shopId) {
        LambdaQueryWrapper<ShopStatisticsTeam> wq=new LambdaQueryWrapper<>();
        wq.eq(ShopStatisticsTeam::getShopId,shopId);
        wq.last("limit 1");
        return getOne(wq);
    }

    @Override
    public void initTeamInfo(Long userId,Long shopId) {
        //获取团队信息
        ShopStatisticsTeam team=getByShopId(shopId);
        if (team==null){
            team=new ShopStatisticsTeam();
            team.setShopId(shopId);
        }
        //先统计3代数据
        List<H2ShopBase> threeGenShops=statistics3genUserNum(userId,team);
        if (CollectionUtils.isNotEmpty(threeGenShops)){
           statistics3gen(threeGenShops,team);
        }
        //团队数据
        statisticsTeam(userId,team);
        team.setUpdateTime(LocalDateTime.now());
        saveOrUpdate(team);
    }

/*    @Override
    public AppShopInfoTeamVo getShopTeam(Long userId) {
        H2ShopBase h2ShopBase=h2ShopBaseService.getByUserId(userId);
        if (null == h2ShopBase){
            throw new QysException(MessageUtils.message("shop.not.exist"));
        }
        AppShopInfoTeamVo appShopInfoTeamVo=new AppShopInfoTeamVo();
        appShopInfoTeamVo.setId(h2ShopBase.getId().toString());
        appShopInfoTeamVo.setName(h2ShopBase.getShopName());
        appShopInfoTeamVo.setAvatarUrl(h2ShopBase.getShopAvatarUrl());
        //获取用户
        H2AppUser user=appUserService.getById(userId.toString());
        appShopInfoTeamVo.setRandomId(user.getUserRandomId());
        //店铺收益
        List<H2AppUser> h2AppUsers=relationService.getLowerLevels(userId);
        List<Long> ids=null;
        if (CollectionUtils.isEmpty(h2AppUsers)){
            ids=new ArrayList<>();
        }else {
            ids=h2AppUsers.stream().map(a->Long.valueOf(a.getId())).collect(Collectors.toList());
        }
        ids.add(userId);
        //店铺收益
        List<String> codes = AccountBusinessTypeEnum.getShopCommissionCode();
        //总佣金
        BigDecimal sumCumulative= financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,null);
        appShopInfoTeamVo.setCumulative(sumCumulative==null?BigDecimal.ZERO:sumCumulative);
        //本周
        BigDecimal weekendCumulative=financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,1);
        appShopInfoTeamVo.setWeekendCumulative(weekendCumulative==null?BigDecimal.ZERO:weekendCumulative);
        //当天
        BigDecimal dayCumulative=financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,2);
        appShopInfoTeamVo.setDayCumulative(dayCumulative==null?BigDecimal.ZERO:dayCumulative);

        ShopStatisticsTeam team=getByShopId(h2ShopBase.getId());
        appShopInfoTeamVo.setDirectNum(team.getDirectNumber());
        appShopInfoTeamVo.setSecondGrandNum(team.getTwoNumber());
        appShopInfoTeamVo.setThirdGrandNum(team.getThreeNumber());
        appShopInfoTeamVo.setTeamNum(team.getLastThreeNum()==null?0:team.getLastThreeNum());
        return appShopInfoTeamVo;
    }

    @Override
    public Page<AppUserInfoTeamDetailVo> getUserShoplist(BaseQuery baseQuery) {
        Page<AppUserInfoTeamDetailVo> page = new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize());
        List<AppUserInfoTeamDetailVo> users=null;
        switch (baseQuery.getId()){
            case "1":
                //查询直推
                List<H2AppUser> users1=relationService.getLowerLevels(SecurityUtils.getUserId(),1);
                if (CollectionUtils.isNotEmpty(users1)){
                    List<H2ShopBase> shops1=h2ShopBaseService.getShopByUserIds(users1.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
                    //直推数（真实+状态正常+充值+V1以上的）
                    List<Long> directShops= shops1.stream().filter(shop-> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                            &&Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                            &&shop.getShopLevelId()>=1//等级V1以上
                            &&Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
                    ).map(H2ShopBase::getId).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(directShops)){
                        users=h2ShopBaseService.getShopbyids(page,directShops);
                    }
                }
                break;

            case "2":
                //查询第二代
                List<H2AppUser> users2=relationService.getLowerLevels(SecurityUtils.getUserId(),2);
                if (CollectionUtils.isNotEmpty(users2)){
                    List<H2ShopBase> shops2=h2ShopBaseService.getShopByUserIds(users2.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
                    //直推数（真实+状态正常+充值+V1以上的）
                    List<Long> twoShops= shops2.stream().filter(shop-> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                            &&Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                            &&shop.getShopLevelId()>=1//等级V1以上
                            &&Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
                    ).map(H2ShopBase::getId).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(twoShops)){
                    users=h2ShopBaseService.getShopbyids(page,twoShops);
                    }
                }
                break;

            case "3":
                //查询第三代
                List<H2AppUser> users3=relationService.getLowerLevels(SecurityUtils.getUserId(),3);
                if (CollectionUtils.isNotEmpty(users3)) {
                    //查询对应店铺
                    List<H2ShopBase> shops3 = h2ShopBaseService.getShopByUserIds(users3.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
                    //直推数（真实+状态正常+充值+V1以上的）
                    List<Long> threeShops = shops3.stream().filter(shop -> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                            && Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                            && shop.getShopLevelId() >= 1//等级V1以上
                            && Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
                    ).map(H2ShopBase::getId).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(threeShops)){
                        users = h2ShopBaseService.getShopbyids(page, threeShops);
                    }
                }
                break;

        }
        page.setRecords(users);
        return page;
    }*/

    @Override
    public AppShopInfoTeamVo getShopTeam(Long userId) {
        H2ShopBase h2ShopBase=h2ShopBaseService.getByUserId(userId);
        if (null == h2ShopBase){
            throw new QysException(MessageUtils.message("shop.not.exist"));
        }
        AppShopInfoTeamVo appShopInfoTeamVo=new AppShopInfoTeamVo();
        appShopInfoTeamVo.setId(h2ShopBase.getId().toString());
        appShopInfoTeamVo.setName(h2ShopBase.getShopName());
        appShopInfoTeamVo.setAvatarUrl(h2ShopBase.getShopAvatarUrl());
        //获取用户
        H2AppUser user=appUserService.getById(userId.toString());
        appShopInfoTeamVo.setRandomId(user.getUserRandomId());
        appShopInfoTeamVo.setInviteNum(0);
        //店铺收益
        List<H2AppUser> h2AppUsers=relationService.getLowerLevels(userId);
        List<Long> ids=null;
        if (CollectionUtils.isEmpty(h2AppUsers)){
            ids=new ArrayList<>();
        }else {
            ids=h2AppUsers.stream().map(a->Long.valueOf(a.getId())).collect(Collectors.toList());
        }
        ids.add(userId);
        //店铺收益
        List<String> codes = AccountBusinessTypeEnum.getShopCommissionCode();
        //总佣金
        BigDecimal sumCumulative= financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,null);
        appShopInfoTeamVo.setCumulative(sumCumulative==null?BigDecimal.ZERO:sumCumulative);
        //本周
        BigDecimal weekendCumulative=financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,1);
        appShopInfoTeamVo.setWeekendCumulative(weekendCumulative==null?BigDecimal.ZERO:weekendCumulative);
        //当天
        BigDecimal dayCumulative=financeShopAccountDetailMapper.getCumulativeIncome(userId,codes,2);
        appShopInfoTeamVo.setDayCumulative(dayCumulative==null?BigDecimal.ZERO:dayCumulative);
        List<Long> direct=getShopSubordinate(userId,1);
        List<Long> secondGrand=getShopSubordinate(userId,2);
        List<Long> thirdGrand=getShopSubordinate(userId,3);
        appShopInfoTeamVo.setDirectNum(direct.size());
        appShopInfoTeamVo.setSecondGrandNum(secondGrand.size());
        appShopInfoTeamVo.setThirdGrandNum(thirdGrand.size());
        appShopInfoTeamVo.setTeamNum(appShopInfoTeamVo.getDirectNum()+appShopInfoTeamVo.getSecondGrandNum()+appShopInfoTeamVo.getThirdGrandNum());
        List<Long> shopIds=new ArrayList<>();
        shopIds.addAll(direct);
        shopIds.addAll(secondGrand);
        shopIds.addAll(thirdGrand);
        if (CollectionUtils.isNotEmpty(shopIds)){
            ShopIncomeConfig shopIncomeConfig=shopIncomeConfigService.get();
            if (null==shopIncomeConfig.getEffectiveShop()){
                return appShopInfoTeamVo;
            }
            LambdaQueryWrapper<FinanceShopAccount> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.in(FinanceShopAccount::getShopId,shopIds);
            queryWrapper.ge(FinanceShopAccount::getTotalBalance,shopIncomeConfig.getEffectiveShop());
            Long count=financeShopAccountMapper.selectCount(queryWrapper);
            appShopInfoTeamVo.setInviteNum(count.intValue());
        }
        return appShopInfoTeamVo;
    }

    public List<Long> getShopSubordinate(Long userId,Integer level){
        List<H2AppUser> userIds=relationService.getLowerLevels(userId,level);
        if (CollectionUtils.isEmpty(userIds)){
            return new ArrayList<>();
        }
        List<H2ShopBase> shopInfos=h2ShopBaseService.getShopByUserIds(userIds.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(shopInfos)){
            return new ArrayList<>();
        }
        return shopInfos.stream().map(H2ShopBase::getId).collect(Collectors.toList());
    }

    @Override
    public Page<AppUserInfoTeamDetailVo> getUserShoplist(BaseQuery baseQuery) {
        Page<AppUserInfoTeamDetailVo> page = new Page<>(baseQuery.getPageNum(), baseQuery.getPageSize());
        List<AppUserInfoTeamDetailVo> users=null;
        switch (baseQuery.getId()){
            case "1":
                //查询直推
                List<Long> directShops=getShopSubordinate(SecurityUtils.getUserId(),1);
                if (CollectionUtils.isNotEmpty(directShops)){
                   users=h2ShopBaseService.getShopbyids(page,directShops);
                }
                break;

            case "2":
                //查询第二代
                List<Long> twoShops=getShopSubordinate(SecurityUtils.getUserId(),2);
                if (CollectionUtils.isNotEmpty(twoShops)){
                    users=h2ShopBaseService.getShopbyids(page,twoShops);
                }
                break;

            case "3":
                //查询第三代
                List<Long> threeShops = getShopSubordinate(SecurityUtils.getUserId(),3);
                if (CollectionUtils.isNotEmpty(threeShops)){
                    users = h2ShopBaseService.getShopbyids(page, threeShops);
                }
                break;
        }
        page.setRecords(users);
        return page;
    }

    @Override
    public Page<AppUserInfoTeamIncomeVO> getShoplistIncome(AppUserInfoTeamIncomeDTO incomeDTO) {
        String userid=SecurityUtils.getUserId().toString();
        //店铺收益
        List<String> codes = AccountBusinessTypeEnum.getShopCommissionCode();
        UserInfoTeamIncomeDTO userInfoTeamIncomeDTO=new UserInfoTeamIncomeDTO();
        BeanUtil.copyProperties(incomeDTO,userInfoTeamIncomeDTO);
        userInfoTeamIncomeDTO.setUserIds(Arrays.asList(userid));
        if (StringUtils.isNoneEmpty(incomeDTO.getCode())){
            userInfoTeamIncomeDTO.setCodeArr(Arrays.asList(incomeDTO.getCode()));
        }else {
            userInfoTeamIncomeDTO.setCodeArr(codes);
        }
        Page<AppUserInfoTeamIncomeVO> page = new Page<>(incomeDTO.getPageNum(), incomeDTO.getPageSize());
        page=financeShopAccountDetailMapper.getShopListIncome(page,userInfoTeamIncomeDTO);
        page.getRecords().forEach(e -> {
            e.setDesc(messageServer.getMsg(FinanceMessageEnum.getEnum(e.getCode())));
            LocalDateTime payDate =e.getPayDate();
            if (null != payDate){
                e.setPayDateLongTime(payDate.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
            }
        });
        return page;
    }

    /**
     * 统计店铺直推数，2代数，3代数,近3代人数,注册人数
     * @param userId
     * @param team
     * @return
     */
    private List<H2ShopBase> statistics3genUserNum(Long userId,ShopStatisticsTeam team){
        List<H2ShopBase> shops=new ArrayList<>();
        //查询直推用户
        List<H2AppUser> users1=relationService.getLowerLevels(userId,1);
        if(CollectionUtils.isEmpty(users1)){
            team.setDirectNumber(0);
            team.setTwoNumber(0);
            team.setThreeNumber(0);
            return new ArrayList<>();
        }
        //查询对应店铺
        List<H2ShopBase> shops1=h2ShopBaseService.getShopByUserIds(users1.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
        if (CollectionUtils.isEmpty(shops1)){
            team.setDirectNumber(0);
        }
        shops.addAll(shops1);
        //直推数（真实+状态正常+充值+V1以上的）
        List<H2ShopBase> directShops= shops1.stream().filter(shop-> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                                        &&Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                                        &&shop.getShopLevelId()>=1//等级V1以上
                                        &&Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
                                ).collect(Collectors.toList());
        team.setDirectNumber(directShops.size());

        //查询2代用户
        List<H2AppUser> users2=relationService.getLowerLevels(userId,2);
        if(CollectionUtils.isEmpty(users2)){
            team.setTwoNumber(0);
        }
        //查询对应店铺
        if(CollectionUtils.isNotEmpty(users2)) {
            List<H2ShopBase> shops2 = h2ShopBaseService.getShopByUserIds(users2.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(shops2)) {
                team.setTwoNumber(0);
            }
            shops.addAll(shops2);
            //2代数（真实+状态正常+充值+V1以上的）
            List<H2ShopBase> twoShops = shops2.stream().filter(shop -> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                    && Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                    && shop.getShopLevelId() >= 1//等级V1以上
                    && Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
            ).collect(Collectors.toList());
            team.setTwoNumber(twoShops.size());
        }

        //查询3代用户
        List<H2AppUser> users3=relationService.getLowerLevels(userId,3);
        if(CollectionUtils.isEmpty(users3)){
            team.setThreeNumber(0);
        }
        //查询对应店铺
        if(CollectionUtils.isNotEmpty(users3)) {
            List<H2ShopBase> shops3 = h2ShopBaseService.getShopByUserIds(users3.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(shops3)) {
                team.setThreeNumber(0);
            }
            shops.addAll(shops3);
            //3代数（真实+状态正常+充值+V1以上的）
            List<H2ShopBase> threeShops = shops3.stream().filter(shop -> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                    && Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                    && shop.getShopLevelId() >= 1//等级V1以上
                    && Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
            ).collect(Collectors.toList());
            team.setThreeNumber(threeShops.size());
        }

        //近3代人数(自己的1.2.3代做判断的真实用户+状态正常+充值用户+V1以上的用户)
        team.setLastThreeNum(team.getDirectNumber()+team.getTwoNumber()+team.getThreeNumber());
        //近3代注册人数(他自己下面的1.2.3代用户统计，判断：状态正常+真实用户)
        List<H2ShopBase> threeRegisterShops= shops.stream().filter(shop-> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                &&Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
        ).collect(Collectors.toList());
        team.setLastThreeRegisterNum(threeRegisterShops.size());
        return shops;
    }


    private void statistics3gen(List<H2ShopBase> shops,ShopStatisticsTeam team){
        List<Long> shopIds=shops.stream().map(H2ShopBase::getId).collect(Collectors.toList());
        //获取对应的统计数据
        List<H2ShopStatisticsInfo> shopStatisticsInfos=h2ShopStatisticsInfoService.getByShopIds(shopIds);
        //近3代充值金额(自己的1.2.3代）
        BigDecimal lastThreeRecharge=BigDecimal.ZERO;
        //近3代提现金额自己的1.2.3代）
        BigDecimal lastThreeWithdrawal=BigDecimal.ZERO;
        //近3代复充金额(1-3代)
        BigDecimal lastThreeGenRecharge=BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(shopStatisticsInfos)){
            for(H2ShopStatisticsInfo info:shopStatisticsInfos){
                lastThreeRecharge=lastThreeRecharge.add(info.getRecharge()!=null?info.getRecharge():BigDecimal.ZERO);
                lastThreeWithdrawal=lastThreeWithdrawal.add(info.getWithdrawal()!=null?info.getWithdrawal():BigDecimal.ZERO);
                lastThreeGenRecharge=lastThreeGenRecharge.add(info.getRechargeMoney()!=null?info.getRechargeMoney():BigDecimal.ZERO);
            }
        }
        team.setLastThreeRecharge(lastThreeRecharge);
        team.setLastThreeWithdrawal(lastThreeWithdrawal);
        team.setLastThreeGenRecharge(lastThreeGenRecharge);
        //充提差
        team.setLastThreeDifference(team.getLastThreeRecharge().subtract(team.getLastThreeWithdrawal()));

        //过期人数(自己下面的1.2.3代 余额小于20+真实用户+状态正常+充值用户)
        //近期新增人数(30天自己下面的1.2.3代 新增首充+真实用户+状态正常)
        //近期过期人数(30天自己下面的1.2.3代 余额小于20+真实用户+状态正常+充值用户)
        //按规则先过滤
        List<H2ShopBase> filterShops= shops.stream().filter(shop-> Objects.equals(shop.getType(), ShopConstant.ShopType.USER)//真实店铺
                &&Objects.equals(shop.getStatus(), ShopConstant.ShopStatus.IN_BUSINESS)//状态正常
                &&Objects.equals(shop.getRecharged(), Constants.YesNoInt.YES)//充过值
        ).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(filterShops)){
            team.setRecentAdd(0);
            team.setExpireNumber(0);
            team.setExpireRecent(0);
            return;
        }
        List<Long> filterShopIds=new ArrayList<>();
        if (filterShops.size()>0){
            filterShopIds=filterShops.stream().map(H2ShopBase::getId).collect(Collectors.toList());
        }

        //余额小于20---过期人数(自己下面的1.2.3代 余额小于20+真实用户+状态正常+充值用户)
        List<Long> ls20Shops=new ArrayList<>();
        if (filterShopIds.size()>0){
            ls20Shops=financeShopAccountService.listShopIdByLessBalance(filterShopIds,new BigDecimal("20"));
            if (ls20Shops==null){
                team.setExpireNumber(0);
            }
            team.setExpireNumber(ls20Shops.size());
        }
        //注册时间小于30天 余额小于20----近期过期人数(30天自己下面的1.2.3代 余额小于20+真实用户+状态正常+充值用户)
        team.setExpireRecent(0);
        if (CollectionUtils.isNotEmpty(ls20Shops)) {
            List<Long> finalLs20Shops = ls20Shops;
            List<H2ShopBase> expireRecentShops = filterShops.stream().filter(shop -> finalLs20Shops.contains(shop.getId())
                            && LocalDateTimeUtil.between(shop.getCreateTime().plusDays(30), LocalDateTime.now()).toDays() < 0)
                    .collect(Collectors.toList());
            if (expireRecentShops==null){
                team.setExpireRecent(0);
            }
            team.setExpireRecent(expireRecentShops.size());
        }

        //新增 首次充值时间小于30天
        team.setRecentAdd(0);
        if (filterShopIds.size()>0){
            List<Long> finalFilterShopIds = filterShopIds;
            List<H2ShopStatisticsInfo> recentAddInfos= shopStatisticsInfos.stream().filter(info -> finalFilterShopIds.contains(info.getShopId())
                    &&LocalDateTimeUtil.between(info.getFirstCharge().plusDays(30), LocalDateTime.now()).toDays()<0).collect(Collectors.toList());
            team.setRecentAdd(recentAddInfos.size());
        }
    }

    private void statisticsTeam(Long userId,ShopStatisticsTeam team){
        //累计团队收益（自己1-n代）
        BigDecimal teamCumulative =BigDecimal.ZERO;
        //团队提现金额(自己的1-n代)
        BigDecimal teamWithdrawal =BigDecimal.ZERO;
        //团队复充金额(1-n代)
        BigDecimal teamRepeatedRecharge =BigDecimal.ZERO;

        //获取团队所有用户
        List<H2AppUser> allUsers=relationService.getGreaterLevels(userId,0);
        if (CollectionUtils.isEmpty(allUsers)){
            team.setTeamWithdrawal(teamWithdrawal);
            team.setTeamRepeatedRecharge(teamRepeatedRecharge);
            team.setTeamCumulative(teamCumulative);
            return;
        }
        //获取团队所有店铺
        List<Long> userIds= allUsers.stream().map(H2AppUser::getId).map(Long::valueOf).collect(Collectors.toList());
        List<H2ShopBase> shops=h2ShopBaseService.getShopByUserIds(userIds);
        if (CollectionUtils.isEmpty(shops)){
            team.setTeamWithdrawal(teamWithdrawal);
            team.setTeamRepeatedRecharge(teamRepeatedRecharge);
            team.setTeamCumulative(teamCumulative);
            return;
        }
        //获取所有店铺的统计信息
        List<Long> shopIds=shops.stream().map(H2ShopBase::getId).collect(Collectors.toList());
        List<H2ShopStatisticsInfo> infos= h2ShopStatisticsInfoService.getByShopIds(shopIds);
        if (CollectionUtils.isEmpty(infos)){
            team.setTeamWithdrawal(teamWithdrawal);
            team.setTeamRepeatedRecharge(teamRepeatedRecharge);
            team.setTeamCumulative(teamCumulative);
            return;
        }
        //统计
        for(H2ShopStatisticsInfo info:infos){
            teamCumulative=teamCumulative.add(info.getCumulative()!=null?info.getCumulative():BigDecimal.ZERO);
            teamWithdrawal=teamWithdrawal.add(info.getWithdrawal()!=null?info.getWithdrawal():BigDecimal.ZERO);
            teamRepeatedRecharge=teamRepeatedRecharge.add(info.getRechargeMoney()!=null?info.getRechargeMoney():BigDecimal.ZERO);
        }
        team.setTeamWithdrawal(teamWithdrawal);
        team.setTeamRepeatedRecharge(teamRepeatedRecharge);
        team.setTeamCumulative(teamCumulative);
    }

    @Override
    public void updateShopExc(List<Long> shopIds){
        log.info("店铺团队数据统计开始....");
        List<H2ShopBase> shops=h2ShopBaseService.listByIds(shopIds);
        if (CollectionUtils.isNotEmpty(shops)){
            for(H2ShopBase shop:shops){
                log.info("shopCode:"+shop.getShopCode()+" 店铺开始统计！");
                this.initTeamInfo(shop.getUserId(),shop.getId());
                log.info("shopCode:"+shop.getShopCode()+" 店铺开始统计结束！");
            }
        }
        log.info("店铺团队数据统计结束！");
    }
}
